{% extends 'base.html' %}
{% load static %}

{% block title %}监控仪表板{% endblock %}

{% block extra_css %}
<style>
    .dashboard-container {
        padding: 20px;
        max-width: 1400px;
        margin: 0 auto;
    }

    .dashboard-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
        padding-bottom: 15px;
        border-bottom: 2px solid #e0e0e0;
    }

    .dashboard-title {
        font-size: 2.5rem;
        font-weight: bold;
        color: #f7f2f2;
        margin: 0;
    }

    .refresh-btn {
        background: linear-gradient(135deg, #28a745, #20c997) !important;
        border: none !important;
        color: white !important;
        padding: 10px 20px !important;
        border-radius: 20px !important;
        font-weight: 500 !important;
        text-decoration: none !important;
        display: inline-flex !important;
        align-items: center !important;
        gap: 8px !important;
        /* 完全移除所有transition效果 */
        transition: none !important;
        box-shadow: 0 2px 10px rgba(40, 167, 69, 0.3) !important;
        font-size: 14px !important;
        cursor: pointer !important;
        position: relative !important;
        /* 明确覆盖可能的transform */
        transform: none !important;
    }

    .refresh-btn:hover:not(.loading) {
        /* 完全不改变任何视觉效果，覆盖所有可能的Bootstrap样式 */
        background: linear-gradient(135deg, #28a745, #20c997) !important;
        color: white !important;
        text-decoration: none !important;
        transform: none !important;
        box-shadow: 0 2px 10px rgba(40, 167, 69, 0.3) !important;
        border-color: transparent !important;
    }

    .refresh-btn:active:not(.loading) {
        /* 完全覆盖Bootstrap的active样式 */
        background: linear-gradient(135deg, #28a745, #20c997) !important;
        color: white !important;
        transform: none !important;
        box-shadow: 0 2px 10px rgba(40, 167, 69, 0.3) !important;
        border-color: transparent !important;
    }

    .refresh-btn.loading {
        cursor: not-allowed !important;
        opacity: 0.8 !important;
        /* 保持原有样式，不改变背景颜色和阴影 */
        background: linear-gradient(135deg, #28a745, #20c997) !important;
        color: white !important;
        transform: none !important;
        box-shadow: 0 2px 10px rgba(40, 167, 69, 0.3) !important;
        border-color: transparent !important;
    }

    .refresh-btn .refresh-icon {
        transition: transform 0.3s ease;
        font-size: 14px;
    }

    .refresh-btn:hover:not(.loading) .refresh-icon {
        transform: rotate(180deg);
    }

    .refresh-btn.loading .refresh-icon {
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        from {
            transform: rotate(0deg);
        }
        to {
            transform: rotate(360deg);
        }
    }

    .metrics-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }

    .metric-card {
        background: white;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        border-left: 4px solid #667eea;
        transition: transform 0.3s ease;
    }

    .metric-card:hover {
        transform: translateY(-5px);
    }

    .metric-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .metric-value {
        font-size: 2rem;
        font-weight: bold;
        color: #333;
        margin-bottom: 5px;
    }

    .metric-change {
        font-size: 12px;
        color: #28a745;
    }

    .metric-change.negative {
        color: #dc3545;
    }

    .servers-section, .alerts-section {
        background: white;
        border-radius: 12px;
        padding: 25px;
        margin-bottom: 30px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    .system-resources-section {
        background: white;
        border-radius: 12px;
        padding: 25px;
        margin-bottom: 30px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    .resource-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
        gap: 20px;
        margin-top: 20px;
    }

    .resource-card {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 20px;
        border-left: 4px solid #28a745;
    }

    .resource-card.cpu {
        border-left-color: #007bff;
    }

    .resource-card.memory {
        border-left-color: #ffc107;
    }

    .resource-card.disk {
        border-left-color: #dc3545;
    }

    .resource-card.network {
        border-left-color: #6f42c1;
    }

    .resource-card.process {
        border-left-color: #17a2b8;
    }

    .resource-card.request {
        border-left-color: #fd7e14;
    }

    .resource-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
    }

    .resource-title {
        font-size: 1.1rem;
        font-weight: 600;
        color: #333;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .resource-usage {
        font-size: 1.5rem;
        font-weight: bold;
        color: #333;
    }

    .resource-details {
        margin-top: 10px;
        font-size: 0.9rem;
        color: #666;
    }

    .resource-details div {
        margin-bottom: 5px;
    }

    .progress-bar {
        width: 100%;
        height: 8px;
        background-color: #e9ecef;
        border-radius: 4px;
        overflow: hidden;
        margin: 10px 0;
    }

    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #28a745, #ffc107, #dc3545);
        border-radius: 4px;
        transition: width 0.3s ease;
    }

    .progress-fill.low {
        background: #28a745;
    }

    .progress-fill.medium {
        background: #ffc107;
    }

    .progress-fill.high {
        background: #dc3545;
    }

    .disk-partitions {
        margin-top: 15px;
    }

    .partition-item {
        background: white;
        border-radius: 6px;
        padding: 10px;
        margin-bottom: 8px;
        border-left: 3px solid #6c757d;
    }

    .partition-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 5px;
    }

    .partition-path {
        font-weight: 600;
        color: #333;
    }

    .partition-usage {
        font-size: 0.9rem;
        color: #666;
    }

    .section-title {
        font-size: 1.5rem;
        font-weight: bold;
        color: #333;
        margin-bottom: 20px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .servers-table, .alerts-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 15px;
    }

    .servers-table th, .servers-table td,
    .alerts-table th, .alerts-table td {
        padding: 12px;
        text-align: left;
        border-bottom: 1px solid #e0e0e0;
        color: #333;
    }

    .servers-table th, .alerts-table th {
        background-color: #f8f9fa;
        font-weight: 600;
        color: #555;
    }

    .status-badge {
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
        text-transform: uppercase;
    }

    .status-healthy {
        background-color: #d4edda;
        color: #155724;
    }

    .status-unhealthy {
        background-color: #f8d7da;
        color: #721c24;
    }

    .alert-level-info {
        background-color: #d1ecf1;
        color: #0c5460;
    }

    .alert-level-warning {
        background-color: #fff3cd;
        color: #856404;
    }

    .alert-level-error {
        background-color: #f8d7da;
        color: #721c24;
    }

    .alert-level-critical {
        background-color: #f5c6cb;
        color: #491217;
    }

    .loading {
        text-align: center;
        padding: 40px;
        color: #666;
    }

    .error-message {
        background-color: #f8d7da;
        color: #721c24;
        padding: 15px;
        border-radius: 8px;
        margin: 20px 0;
    }

    .clear-alerts-btn {
        background: #dc3545;
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 6px;
        cursor: pointer;
        font-size: 12px;
        margin-left: auto;
    }

    .clear-alerts-btn:hover {
        background: #c82333;
    }

    .last-updated {
        font-size: 12px;
        color: #666;
        text-align: right;
        margin-top: 10px;
    }
</style>
{% endblock %}

{% block content %}
<div class="dashboard-container">
    <div class="dashboard-header">
        <h1 class="dashboard-title">🔍 监控仪表板</h1>
        <button class="refresh-btn" onclick="refreshDashboard()" id="refresh-btn">
            <i class="fas fa-sync-alt refresh-icon"></i> <span class="refresh-text">刷新数据</span>
        </button>
    </div>

    <div id="loading" class="loading">
        <div>⏳ 正在加载监控数据...</div>
    </div>

    <div id="error-container" style="display: none;"></div>

    <div id="dashboard-content" style="display: none;">
        <!-- 系统指标 -->
        <div class="metrics-grid" id="metrics-grid">
            <!-- 动态生成指标卡片 -->
        </div>

        <!-- 服务器状态 -->
        <div class="servers-section">
            <div class="section-title">
                🖥️ 服务器状态
            </div>
            <table class="servers-table">
                <thead>
                    <tr>
                        <th>战斗ID</th>
                        <th>对战双方</th>
                        <th>回合进度</th>
                        <th>进程ID</th>
                        <th>端口</th>
                        <th>状态</th>
                        <th>持续时间</th>
                        <th>CPU使用率</th>
                        <th>内存使用</th>
                    </tr>
                </thead>
                <tbody id="servers-tbody">
                    <!-- 动态生成服务器状态 -->
                </tbody>
            </table>
        </div>

        <!-- 最近告警 -->
        <div class="alerts-section">
            <div class="section-title">
                🚨 最近告警
                <!-- <button class="clear-alerts-btn" onclick="generateTestAlerts()" style="background: #28a745; margin-right: 10px;">
                    生成测试告警
                </button> -->
                <button class="clear-alerts-btn" onclick="clearAllAlerts()">
                    清除所有告警
                </button>
            </div>
            <table class="alerts-table">
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>类型</th>
                        <th>级别</th>
                        <th>消息</th>
                        <th>战斗ID</th>
                    </tr>
                </thead>
                <tbody id="alerts-tbody">
                    <!-- 动态生成告警信息 -->
                </tbody>
            </table>
        </div>

        <!-- 系统资源 -->
        <div class="system-resources-section">
            <div class="section-title">
                📊 系统资源
            </div>
            <div class="resource-grid" id="resource-grid">
                <!-- 动态生成系统资源信息 -->
            </div>
        </div>

        <div class="last-updated" id="last-updated">
            <!-- 最后更新时间 -->
        </div>
    </div>
</div>

<script>
let refreshInterval;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadDashboardData();
    // 每30秒自动刷新
    refreshInterval = setInterval(loadDashboardData, 30000);
});

// 手动刷新
function refreshDashboard() {
    const refreshBtn = document.getElementById('refresh-btn');
    const refreshIcon = refreshBtn.querySelector('.refresh-icon');
    const refreshText = refreshBtn.querySelector('.refresh-text');

    // 保存原始状态
    const originalIconClass = refreshIcon.className;
    const originalText = refreshText.textContent;

    // 添加加载状态
    refreshIcon.className = 'fas fa-spinner fa-spin refresh-icon';
    refreshText.textContent = '刷新中...';
    refreshBtn.disabled = true;
    refreshBtn.classList.add('loading');

    // 加载数据
    loadDashboardData().finally(() => {
        // 恢复原始状态
        setTimeout(() => {
            refreshIcon.className = originalIconClass;
            refreshText.textContent = originalText;
            refreshBtn.disabled = false;
            refreshBtn.classList.remove('loading');
        }, 300); // 稍微延迟一下，让用户看到加载完成的反馈
    });
}

// 加载仪表板数据
async function loadDashboardData() {
    try {
        const response = await fetch('/battles/api/monitoring/metrics/');
        const result = await response.json();

        if (result.status === 'success') {
            renderDashboard(result.data);
            document.getElementById('loading').style.display = 'none';
            document.getElementById('error-container').style.display = 'none';
            document.getElementById('dashboard-content').style.display = 'block';
        } else {
            showError('API错误: ' + (result.error || '未知错误'));
        }
    } catch (error) {
        console.error('加载监控数据失败:', error);
        showError('网络错误: ' + error.message);
    }
}

// 渲染仪表板
function renderDashboard(data) {
    renderMetrics(data.metrics);
    renderServers(data.servers_status);
    renderAlerts(data.recent_alerts);
    renderSystemResources(data.metrics); // 使用metrics中的系统资源数据

    // 更新最后更新时间
    const lastUpdated = new Date(data.timestamp).toLocaleString('zh-CN');
    document.getElementById('last-updated').textContent = `最后更新: ${lastUpdated}`;
}

// 渲染系统指标
function renderMetrics(metrics) {
    const grid = document.getElementById('metrics-grid');
    grid.innerHTML = '';

    const metricCards = [
        {
            title: '活跃战斗数',
            value: metrics.active_battles || 0,
            icon: '⚔️'
        },
        {
            title: '运行中服务器',
            value: metrics.running_servers || 0,
            icon: '🖥️'
        },
        {
            title: '总告警数',
            value: metrics.total_alerts || 0,
            icon: '🚨'
        },
        {
            title: '系统运行时间',
            value: formatUptime(metrics.uptime_seconds || 0),
            icon: '⏱️'
        },
        {
            title: 'CPU使用率',
            value: metrics.cpu?.usage_percent ? `${metrics.cpu.usage_percent.toFixed(1)}%` : 'N/A',
            icon: '🔥'
        },
        {
            title: '内存使用率',
            value: metrics.memory?.usage_percent ? `${metrics.memory.usage_percent.toFixed(1)}%` : 'N/A',
            icon: '💾'
        }
    ];

    metricCards.forEach(metric => {
        const card = document.createElement('div');
        card.className = 'metric-card';
        card.innerHTML = `
            <div class="metric-title">${metric.icon} ${metric.title}</div>
            <div class="metric-value">${metric.value}</div>
        `;
        grid.appendChild(card);
    });
}

// 渲染系统资源
function renderSystemResources(metrics) {
    const grid = document.getElementById('resource-grid');
    grid.innerHTML = '';

    if (!metrics) {
        grid.innerHTML = '<div style="text-align: center; color: #666; grid-column: 1 / -1;">系统资源信息不可用</div>';
        return;
    }

    // 调试信息：打印metrics结构
    console.log('System metrics data:', metrics);

    // CPU 资源卡片
    const cpuCard = createResourceCard('cpu', '🔥 CPU', metrics.cpu?.usage_percent, {
        '核心数': metrics.cpu?.count || 'N/A',
        '当前频率': metrics.cpu?.freq_current ? `${metrics.cpu.freq_current.toFixed(0)} MHz` : 'N/A',
        '最大频率': metrics.cpu?.freq_max ? `${metrics.cpu.freq_max.toFixed(0)} MHz` : 'N/A',
        '负载平均': metrics.cpu?.load_average ? metrics.cpu.load_average.join(', ') : 'N/A'
    });
    grid.appendChild(cpuCard);

    // 内存资源卡片
    const memoryCard = createResourceCard('memory', '💾 内存', metrics.memory?.usage_percent, {
        '总内存': metrics.memory?.total_formatted || formatBytes(metrics.memory?.total),
        '已使用': metrics.memory?.used_formatted || formatBytes(metrics.memory?.used),
        '可用': metrics.memory?.available_formatted || formatBytes(metrics.memory?.available)
    });
    grid.appendChild(memoryCard);

    // 磁盘资源卡片
    const diskCard = createDiskResourceCard({
        total_usage_percent: metrics.disk?.usage_percent,
        total_space: metrics.disk?.total,
        used_space: metrics.disk?.used,
        free_space: metrics.disk?.free,
        total_formatted: metrics.disk?.total_formatted,
        used_formatted: metrics.disk?.used_formatted,
        free_formatted: metrics.disk?.free_formatted,
        partitions: metrics.disk?.partitions || []
    });
    grid.appendChild(diskCard);

    // 网络资源卡片
    const networkCard = createResourceCard('network', '🌐 网络', null, {
        '发送': metrics.network?.io_sent_formatted || formatBytes(metrics.network?.io_sent),
        '接收': metrics.network?.io_recv_formatted || formatBytes(metrics.network?.io_recv),
        '连接数': metrics.network?.connections || 'N/A',
        '启动时间': metrics.system?.boot_time ? new Date(metrics.system.boot_time * 1000).toLocaleString() : 'N/A'
    });
    grid.appendChild(networkCard);

    // 进程数资源卡片
    const processCard = createResourceCard('process', '⚙️ 进程', null, {
        '总进程数': metrics.processes?.total_count || 'N/A',
        'Python进程': metrics.processes?.python_count || 'N/A',
        'Django进程': metrics.processes?.django_count || 'N/A'
    });
    grid.appendChild(processCard);

    // 请求数资源卡片
    const requestCard = createResourceCard('request', '📊 请求', null, {
        '总请求数': metrics.requests?.total_count || 'N/A',
        '每分钟请求': metrics.requests?.per_minute || 'N/A'
    });
    grid.appendChild(requestCard);
}

// 创建资源卡片
function createResourceCard(type, title, usagePercent, details) {
    const card = document.createElement('div');
    card.className = `resource-card ${type}`;

    let progressBar = '';
    let usageDisplay = '';

    if (usagePercent !== null && usagePercent !== undefined) {
        const progressClass = usagePercent < 50 ? 'low' : usagePercent < 80 ? 'medium' : 'high';
        progressBar = `
            <div class="progress-bar">
                <div class="progress-fill ${progressClass}" style="width: ${usagePercent}%"></div>
            </div>
        `;
        usageDisplay = `<div class="resource-usage">${usagePercent.toFixed(1)}%</div>`;
    }

    const detailsHtml = Object.entries(details).map(([key, value]) =>
        `<div><strong>${key}:</strong> ${value}</div>`
    ).join('');

    card.innerHTML = `
        <div class="resource-header">
            <div class="resource-title">${title}</div>
            ${usageDisplay}
        </div>
        ${progressBar}
        <div class="resource-details">
            ${detailsHtml}
        </div>
    `;

    return card;
}

// 创建磁盘资源卡片
function createDiskResourceCard(diskData) {
    const card = document.createElement('div');
    card.className = 'resource-card disk';

    let partitionsHtml = '';
    if (diskData.partitions && diskData.partitions.length > 0) {
        partitionsHtml = `
            <div class="disk-partitions">
                ${diskData.partitions.map(partition => {
                    const usagePercent = partition.usage_percent || 0;
                    const progressClass = usagePercent < 50 ? 'low' : usagePercent < 80 ? 'medium' : 'high';
                    return `
                        <div class="partition-item">
                            <div class="partition-header">
                                <div class="partition-path">${partition.mountpoint}</div>
                                <div class="partition-usage">${usagePercent.toFixed(1)}%</div>
                            </div>
                            <div class="progress-bar">
                                <div class="progress-fill ${progressClass}" style="width: ${usagePercent}%"></div>
                            </div>
                            <div style="font-size: 0.8rem; color: #666;">
                                ${formatBytes(partition.used)} / ${formatBytes(partition.total)}
                            </div>
                        </div>
                    `;
                }).join('')}
            </div>
        `;
    }

    const totalUsagePercent = diskData.total_usage_percent || 0;
    const progressClass = totalUsagePercent < 50 ? 'low' : totalUsagePercent < 80 ? 'medium' : 'high';

    card.innerHTML = `
        <div class="resource-header">
            <div class="resource-title">💽 磁盘</div>
            <div class="resource-usage">${totalUsagePercent.toFixed(1)}%</div>
        </div>
        <div class="progress-bar">
            <div class="progress-fill ${progressClass}" style="width: ${totalUsagePercent}%"></div>
        </div>
        <div class="resource-details">
            <div><strong>总空间:</strong> ${diskData.total_formatted || formatBytes(diskData.total_space)}</div>
            <div><strong>已使用:</strong> ${diskData.used_formatted || formatBytes(diskData.used_space)}</div>
            <div><strong>可用:</strong> ${diskData.free_formatted || formatBytes(diskData.free_space)}</div>
        </div>
        ${partitionsHtml}
    `;

    return card;
}

// 格式化字节数
function formatBytes(bytes) {
    if (!bytes || bytes === 0) return '0 B';

    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 格式化持续时间
function formatDuration(seconds) {
    if (!seconds || seconds < 0) return '0秒';

    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);

    if (hours > 0) {
        return `${hours}小时${minutes}分钟`;
    } else if (minutes > 0) {
        return `${minutes}分钟${secs}秒`;
    } else {
        return `${secs}秒`;
    }
}

// 渲染服务器状态
function renderServers(servers) {
    const tbody = document.getElementById('servers-tbody');
    tbody.innerHTML = '';

    if (servers.length === 0) {
        tbody.innerHTML = '<tr><td colspan="9" style="text-align: center; color: #666;">暂无运行中的服务器</td></tr>';
        return;
    }

    servers.forEach(server => {
        const row = document.createElement('tr');
        const statusClass = server.is_healthy ? 'status-healthy' : 'status-unhealthy';
        const statusText = server.is_healthy ? '健康' : '异常';

        // 格式化对战双方信息
        let battleInfo = '-';
        if (server.player1_name && server.player2_name) {
            battleInfo = `${server.player1_name} vs ${server.player2_name}`;
        } else if (server.player1_name || server.player2_name) {
            battleInfo = `${server.player1_name || server.player2_name} (单人)`;
        }

        // 格式化回合进度信息
        let roundProgress = '-';
        if (server.round_progress) {
            roundProgress = server.round_progress;
            // 如果有当前回合和总回合数，添加进度条样式
            if (server.current_round !== undefined && server.total_rounds !== undefined) {
                const progressPercent = server.total_rounds > 0 ? (server.current_round / server.total_rounds * 100) : 0;
                const progressClass = progressPercent < 30 ? 'low' : progressPercent < 70 ? 'medium' : 'high';
                roundProgress = `
                    <div style="display: flex; align-items: center; gap: 8px;">
                        <span style="font-weight: 600;">${server.round_progress}</span>
                        <div style="width: 60px; height: 6px; background: #e9ecef; border-radius: 3px; overflow: hidden;">
                            <div style="width: ${progressPercent}%; height: 100%; background: ${progressClass === 'low' ? '#28a745' : progressClass === 'medium' ? '#ffc107' : '#dc3545'}; transition: width 0.3s ease;"></div>
                        </div>
                    </div>
                `;
            }
        }

        // 格式化进程ID
        const pidInfo = server.pid ? server.pid : '-';

        // 格式化持续时间
        const duration = server.duration_seconds ? formatDuration(server.duration_seconds) : '-';

        row.innerHTML = `
            <td>${server.battle_id}</td>
            <td>${battleInfo}</td>
            <td>${roundProgress}</td>
            <td>${pidInfo}</td>
            <td>${server.port}</td>
            <td><span class="status-badge ${statusClass}">${statusText}</span></td>
            <td>${duration}</td>
            <td>${server.cpu_percent.toFixed(1)}%</td>
            <td>${server.memory_mb.toFixed(1)} MB</td>
        `;
        tbody.appendChild(row);
    });
}

// 渲染告警信息
function renderAlerts(alerts) {
    const tbody = document.getElementById('alerts-tbody');
    tbody.innerHTML = '';

    if (alerts.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #666;">暂无告警信息</td></tr>';
        return;
    }

    // 添加调试信息
    console.log('告警数据:', alerts);

    alerts.forEach(alert => {
        console.log('单个告警:', alert);
        const row = document.createElement('tr');
        const levelClass = `alert-level-${alert.level.toLowerCase()}`;
        const time = new Date(alert.timestamp).toLocaleString('zh-CN');

        // 安全地访问属性，添加默认值
        const alertType = alert.type || alert.alert_type || '未知类型';
        const alertLevel = alert.level || '未知级别';
        const alertMessage = alert.message || '无消息';
        const battleId = alert.battle_id || (alert.metadata && alert.metadata.battle_id) || '-';

        row.innerHTML = `
            <td>${time}</td>
            <td>${alertType}</td>
            <td><span class="status-badge ${levelClass}">${alertLevel}</span></td>
            <td>${alertMessage}</td>
            <td>${battleId}</td>
        `;
        tbody.appendChild(row);
    });
}

// 清除所有告警
async function clearAllAlerts() {
    if (!confirm('确定要清除所有告警吗？')) {
        return;
    }

    try {
        const response = await fetch('/battles/api/monitoring/clear-alerts/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({})
        });

        const result = await response.json();
        if (result.status === 'success') {
            alert('告警已清除');
            loadDashboardData();
        } else {
            alert('清除告警失败: ' + (result.error || '未知错误'));
        }
    } catch (error) {
        alert('网络错误: ' + error.message);
    }
}

// 生成测试告警
async function generateTestAlerts() {
    if (!confirm('确定要生成测试告警吗？')) {
        return;
    }

    try {
        const response = await fetch('/battles/api/monitoring/generate-test-alerts/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({})
        });

        const result = await response.json();
        if (result.status === 'success') {
            alert(`测试告警已生成！生成了 ${result.alerts_generated} 个告警`);
            loadDashboardData();
        } else {
            alert('生成测试告警失败: ' + (result.error || '未知错误'));
        }
    } catch (error) {
        alert('网络错误: ' + error.message);
    }
}

// 显示错误信息
function showError(message) {
    const container = document.getElementById('error-container');
    container.innerHTML = `<div class="error-message">❌ ${message}</div>`;
    container.style.display = 'block';
    document.getElementById('loading').style.display = 'none';
    document.getElementById('dashboard-content').style.display = 'none';
}

// 格式化运行时间
function formatUptime(seconds) {
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);

    if (days > 0) {
        return `${days}天 ${hours}小时`;
    } else if (hours > 0) {
        return `${hours}小时 ${minutes}分钟`;
    } else {
        return `${minutes}分钟`;
    }
}

// 获取CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 页面卸载时清除定时器
window.addEventListener('beforeunload', function() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
});
</script>
{% endblock %}